package com.java2007.zhangyu.restaurant.controller;

import com.java2007.zhangyu.restaurant.constant.ServletConstant;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author zy
 * @Version
 * @date 2021/01/26
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String methodStr = request.getParameter("method");
        try {
            //获取 method业务鉴别字符串，获取相应的业务、方法(通过反射获取)
            Method method = this.getClass().getDeclaredMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);
            //调用目标业务 方法
            Object object = method.invoke(this, request, response);

            if(object != null) {
                if(object instanceof String) {
                    String result = (String) object;
                    String url = null;
                    //判断是否转发还是转定向，还是直接响应字符串
                    if(result.startsWith(ServletConstant.PRE_FORWARD)){
                        //转发: forward:
                        //   /backend/detail/foodtype/food-type-list.jsp
                        url = result.substring(result.indexOf(ServletConstant.TAG) + 1);
                        request.getRequestDispatcher(url).forward(request, response);
                    } else if(result.startsWith(ServletConstant.PRE_REDIRECT)){
                        //重定向: redirect:
                        url = result.substring(result.indexOf(ServletConstant.TAG) + 1);
                        response.sendRedirect(request.getContextPath() + url);
                    } else {
                        //其他: 直接响应字符串
                        response.getWriter().write(result);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
